﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace XP_More
{
	public class VmInfo
	{
		private string m_vmcxFile = "";
		private string m_name = "";
		private string m_state = "";
		private string m_vmcFile = "";
		private string m_vhdFile = "";
		private string m_vsvFile = "";
		private string m_comment = "";

		// Initialize an empty VM descriptor
		public VmInfo()
		{
		}

		// Initialize a VM descriptor with the given details
		public VmInfo(string vmcxFile, string state, string vmcFile,
			string vhdFile, string vsvFile, string comment)
		{
			m_vmcxFile = vmcxFile;
			m_name = GetVmName(vmcxFile);
			m_state = state;
			m_vmcFile = vmcFile;
			m_vhdFile = vhdFile;
			m_vsvFile = vsvFile;
			m_comment = comment;
		}

		// Initialize a VM descriptor with the details found in vmcxFile
		public VmInfo(string vmcxFile)
		{
			LoadFile(vmcxFile);
		}

		// Load the details found in vmcxFile
		public void LoadFile(string vmcxFile)
		{
			XDocument xmlDoc = XDocument.Load(vmcxFile);
			XElement vmDescr, elem;

			m_vmcxFile = vmcxFile;
			m_name = GetVmName(vmcxFile);

			vmDescr = xmlDoc.Element("vm_description");

			elem = vmDescr.Element("vmstate");
			m_state = (elem != null) ? elem.Value : "(unknown)";
			elem = vmDescr.Element("primary_disk1");
			m_vhdFile = (elem != null) ? elem.Value : "(unknown)";
			elem = vmDescr.Element("vmc_path");
			m_vmcFile = (elem != null) ? elem.Value : "(unknown)";
			elem = vmDescr.Element("notes");
			m_comment = (elem != null) ? elem.Value : "(unknown)";
			GetVsvFile();
		}

		public string Vmcx { get { return m_vmcxFile; } }
		public string Name { get { return m_name; } }
		public string State { get { return m_state; } }
		public string Vmc { get { return m_vmcFile; } }
		public string Vhd { get { return m_vhdFile; } }
		public string Vsv { get { return m_vsvFile; } }
		public string Comment { get { return m_comment; } }

		private string GetVmName(string vmcxFile)
		{
			int nameBegin = vmcxFile.LastIndexOf('\\');
			int nameEnd = vmcxFile.Length - 6;	// Len(".vmcx"), zero based
			string name = vmcxFile.Substring(nameBegin + 1, nameEnd - nameBegin);
			return name;
		}

		private void GetVsvFile()
		{
			m_vsvFile = "";
			string vsvFile = m_vmcFile.ToLower().Replace(".vmc", ".vsv");
			if (File.Exists(vsvFile))
				m_vsvFile = vsvFile;
		}

	}
}
